package middleware

import (
	"log"
	"os"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

const (
	mysqlAddress  = "MYSQL_ADDRESS"
	mysqlUser     = "MYSQL_USERNAME"
	mysqlPassword = "MYSQL_PASSWORD"
)

type KeyValue struct {
	Name  string `db:"name"`
	Value string `db:"value"`
}

func (kv *KeyValue) String() string {
	return "name = " + kv.Name + ", value = " + kv.Value
}

type Mysql struct {
	db *sqlx.DB
}

func NewMysqlClient() Mysql {
	db, err := sqlx.Connect("mysql",
		composeDataSource(os.Getenv(mysqlUser), os.Getenv(mysqlPassword), os.Getenv(mysqlAddress), "container-monitor"))
	if err != nil {
		log.Println("Failed to connect to mysql")
		panic(err)
	}
	log.Printf("Start MySql Client, address: %s\n", os.Getenv(mysqlAddress))

	return Mysql{db: db}
}

func (c Mysql) Close() {
	_ = c.db.Close()
}

func (c Mysql) Visit() {
	var result []KeyValue
	// Execute the query
	err := c.db.Select(&result, "SELECT * FROM dummy")
	if err != nil {
		log.Printf("Fail to query mysql: %v", err)
		return
	}
	log.Printf("Query mysql: %v", result)
}

func composeDataSource(user string, password string, address string, database string) string {
	dataSource := user + ":" + password + "@tcp(" + address + ")/" + database
	log.Print(dataSource)
	return dataSource
}
